/*
 *    Copyright (C) 2011-2012 Hai Bison
 *
 *    See the file LICENSE at the root directory of this project for copying
 *    permission.
 */

/*
 * DialogSignIn.java
 *
 * Created on Sep 11, 2011, 9:07:44 AM
 */
package group.pals.mailgate;

import group.pals.mailgate.preferences.Preferences;
import group.pals.utils.sys.MessageBox;
import group.pals.utils.ui.Utils;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;

/**
 *
 * @author Hai Bison
 */
public class DialogSignIn extends javax.swing.JDialog {

    private final group.pals.mailgate.utils.Utils _Utils;
    private boolean loginPassed;

    /** Creates new form DialogSignIn */
    public DialogSignIn(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        this._Utils = group.pals.mailgate.utils.Utils.getInstance();

        initUI();
        initActions();
        initListeners();

        loginPassed = false;
    }

    private void initUI() {
        setTitle(String.format("%s - Sign In", _Utils.getAppTitle()));
        setIconImage(_Utils.getMainIcon().getImage());

        Utils.setWindowCenterScreen(this, 0);
        txtPassword.setComponentPopupMenu(
                group.pals.mailgate.ui.Utils.getInstance().getEditorPopupMenu());
    }

    private void initActions() {
        actionSignIn = new ActionSignIn();
        actionExit = new ActionExit();

        btnSignIn.setAction(actionSignIn);
        btnExit.setAction(actionExit);
    }

    private void initListeners() {
        //key listener
        KeyListener keyListener = new KeyListener() {

            public void keyTyped(KeyEvent e) {
                doHandle(e);
            }

            public void keyPressed(KeyEvent e) {
                doHandle(e);
            }

            public void keyReleased(KeyEvent e) {
                doHandle(e);
            }

            private void doHandle(KeyEvent e) {
                switch (e.getKeyCode()) {
                    case KeyEvent.VK_ENTER: {
                        if (!btnExit.equals(e.getComponent())) {
                            btnSignIn.doClick();
                        }
                        break;
                    }//VK_ENTER

                    case KeyEvent.VK_ESCAPE: {
                        System.exit(0);
                        break;
                    }//VK_ESCAPE
                }//switch
            }
        };

        txtPassword.addKeyListener(keyListener);
        btnSignIn.addKeyListener(keyListener);
        btnExit.addKeyListener(keyListener);

        //window listener
        addWindowListener(new java.awt.event.WindowAdapter() {

            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                if (!loginPassed) {
                    System.exit(0);
                }
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtPassword = new javax.swing.JPasswordField();
        btnSignIn = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtPassword.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Enter password:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 1, 12), java.awt.Color.blue)); // NOI18N

        btnSignIn.setText("jButton1");

        btnExit.setText("jButton2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnSignIn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExit)
                        .addGap(16, 16, 16))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExit)
                    .addComponent(btnSignIn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    /**
     * @param args the command line arguments
     */
//  public static void main(String args[]) {
//    /* Set the Nimbus look and feel */
//    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//     */
//    try {
//      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//        if ("Nimbus".equals(info.getName())) {
//          javax.swing.UIManager.setLookAndFeel(info.getClassName());
//          break;
//        }
//      }
//    } catch (ClassNotFoundException ex) {
//      java.util.logging.Logger.getLogger(DialogSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (InstantiationException ex) {
//      java.util.logging.Logger.getLogger(DialogSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (IllegalAccessException ex) {
//      java.util.logging.Logger.getLogger(DialogSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//      java.util.logging.Logger.getLogger(DialogSignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//    }
//    //</editor-fold>
//
//    /* Create and display the dialog */
//    java.awt.EventQueue.invokeLater(new Runnable() {
//
//      public void run() {
//        DialogSignIn dialog = new DialogSignIn(new javax.swing.JFrame(), true);
//        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
//
//          @Override
//          public void windowClosing(java.awt.event.WindowEvent e) {
//            System.exit(0);
//          }
//        });
//        dialog.setVisible(true);
//      }
//    });
//  }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnSignIn;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables

    /*----------------------------------------------------------------------------
     * ACTIONS
     */

    /*----------------------------------------------------------------------------
     * ActionSignIn
     */
    private ActionSignIn actionSignIn;

    private class ActionSignIn extends AbstractAction {

        public ActionSignIn() {
            super("Sign In");
        }

        public void actionPerformed(ActionEvent e) {
            Preferences preferences = Preferences.getInstance();
            if (preferences.userLogin(new String(txtPassword.getPassword()))) {
                loginPassed = true;
                dispose();
            } else {
                MessageBox.showErrMsg(null, null, "Invalid Password!");
                txtPassword.requestFocusInWindow();
                txtPassword.selectAll();
            }
        }
    }

    /*----------------------------------------------------------------------------
     * ActionExit
     */
    private ActionExit actionExit;

    private class ActionExit extends AbstractAction {

        public ActionExit() {
            super("Exit");
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke((char) KeyEvent.VK_ESCAPE));
        }

        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }
}
